package cn.com.czpb.client.module.nanning;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.viewpagerindicator.TabPageIndicator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.App;
import cn.com.czpb.client.app.MyActivitymanager;
import cn.com.czpb.client.model.WeatherBean;
import cn.com.czpb.client.model.event.CurrentCityEvent;
import cn.com.czpb.client.model.event.CurrentCityEventForMainAndZiXun;
import cn.com.czpb.client.model.event.CurrentSecondCityEvent;
import cn.com.czpb.client.model.news.AreaChannelBean;
import cn.com.czpb.client.model.news.AreaChannelEntity;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.news.NewsChannelBean;
import cn.com.czpb.client.module.nanning.adapter.CityFragmentPagerAdapter;
import cn.com.czpb.client.module.nanning.fragment.NanningItemFragment;
import cn.com.czpb.client.module.news.NewsBaseFragment;
import cn.com.czpb.client.module.news.dialog.ChangeCityDialog;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.SPUtil;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/7/3.
 */

public class NanningFragment extends NewsBaseFragment implements BaseQuickAdapter.OnItemChildClickListener{

    @BindView(R.id.tv_weather_id)
    TextView tvWeatherId;//天气
    @BindView(R.id.ll_city_id)
    LinearLayout llCityId;//城市点击事件LL
    Unbinder unbinder1;
    @BindView(R.id.tv_city_id)
    TextView tvCityId;//城市
    @BindView(R.id.city_tablepage_ll)
    RelativeLayout cityTablepageLl;//区县RL
    @BindView(R.id.city_indicator)
    TabPageIndicator indicator;//区县选择器
    @BindView(R.id.city_button)
    RelativeLayout cityButton;//add、delete区县
    @BindView(R.id.city_pager)
    ViewPager citypager;//各区县Fragment的容器
    private CityFragmentPagerAdapter adapter;
    private List<NewsBaseFragment> newsItemFragmentList;
    private int position = -1;
    // 是否刷新最新数据
    private boolean isNeedRefresh = false;
    private NewsChannelBean channelbean;
    private String mTitle;
    private List<AreaChannelBean> mList;

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private static final String[] PERMISSIONS = new String[]{
//            Manifest.permission.CAMERA,//照相机权限
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,//写入存储的权限;
//            Manifest.permission.READ_PHONE_STATE,//写入存储的权限;
            Manifest.permission.ACCESS_COARSE_LOCATION,//地址
    };

    @Override
    public int setMyContentView() {
        return R.layout.fragment_nanning;
    }

    public static final NanningFragment newInstance() {
        NanningFragment fragment = new NanningFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }
    @Override
    public void initView() {
        if(spu.getCurrentCountry() != null){
            tvCityId.setText(spu.getCurrentCountry().getChild().get(spu.getCurrentCountryPosition()).getName());
        }else{
            tvCityId.setText(spu.getCurrentCity());
        }
        getWeather();
        position = getArguments().getInt("position");
        final LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        adapter = new CityFragmentPagerAdapter(fm, activity);
        citypager.setAdapter(adapter);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        getChannelJson();
        LogUtils.i("position-->" + position);
        LogUtils.i("isNeedRefresh-->" + isNeedRefresh);
        mList = new ArrayList<>();
//        getChannelList();//得到当前城市的区县，设置到选择器


        checkLocationPermission();


    }

    private void checkLocationPermission() {
        RxPermissions.getInstance(activity)
                .request(PERMISSIONS)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        LogUtils.i("granted-->"+granted);
                        if (!granted) {
                            String oldcity = spu.getCurrentLocation();
                            if("0".equals(oldcity)){
                                ChangeCurrentCity("南宁");
                                showCityDialog();
                            }

                        } else {
                            getLocation();
                        }
                    }
                });


    }
    public void getLocation() {
        LogUtils.i("位置-->");
        mLocationClient = new LocationClient(activity);
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location){
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
            checkCity(city);

        }
    }
    private void checkCity(String city0) {
        String city="";
        LogUtils.i("位置-city->"+city0);
        if (city0.contains("市")){
            city = city0.substring(0,city0.length()-1);
        }

        LogUtils.i("位置-city->"+city);
        String oldcity = spu.getCurrentLocation();
        //首次登录 没有保存定位地址
        LogUtils.i("位置-oldcity->"+oldcity);
        if("0".equals(oldcity)){
            //如果定位在广西
            if (App.citys.contains(city)){
                LogUtils.i("位置-1->"+city);
                spu.setCurrentLocation(city);
                ChangeCurrentCity(city);
            }
        }else{
            //新定位城市 和旧城市 一样 什么也不做
            //新城市不同于 就城市
            if (!oldcity.equals(city)){
                //新城市在广西
                LogUtils.i("位置-2->"+city);
                if (App.citys.contains(city)){
                    LogUtils.i("位置-3->"+city);
                    spu.setCurrentLocation(city);
                    showCityDialog(city);
                    //新城市不在广西,什么也不做
                }else{

                }
            }
        }
    }


    private void showCityDialog() {

        final ChangeCityDialog changeCityDialog = new ChangeCityDialog(
                activity, R.style.ChangeCitydialog); // 0为修改昵称 1为修改个人签名
        changeCityDialog.show();
        changeCityDialog.setOnChangeCityListener(new ChangeCityDialog.OnChangeCityListener() {
            @Override
            public void onClick(String city) {
                LogUtils.i(city);
                ChangeCurrentCity(city);
                changeCityDialog.dismiss();
            }
        });
    }
    private void showCityDialog(final String city) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        LogUtils.i("位置-4->"+city);
        AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(activity,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
        normalDialog.setTitle("定位到您在  "+city+"\n"+
                "是否切换到当前城市");
        normalDialog.setPositiveButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        LogUtils.i("位置-5->"+city);
                    }
                });
        normalDialog.setNegativeButton("切换",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        LogUtils.i("位置-6->"+city);
                        ChangeCurrentCity(city);
                    }
                });
        // 显示
        normalDialog.show();
    }
    private void ChangeCurrentCity(String city) {
        spu.setCurrentLocation(city);
        try{
            LogUtils.i("位置-7->"+city);
            HashMap<String,AreaChannelBean> map = spu.getHashMapData("cityMap", AreaChannelBean.class);
            AreaChannelBean bean = map.get(city);
            LogUtils.i("位置-8->"+bean.getFid());
            spu.setCurrentCity(bean.getName());
            spu.setCurrentCityId(bean.getId());
            spu.setCurrentCounty(null);
            spu.setIsLarge(bean.getIslarge());
            CurrentCityEventForMainAndZiXun event2 = new CurrentCityEventForMainAndZiXun();
            EventBus.getDefault().post(event2);
            CurrentCityEvent event = new CurrentCityEvent();
            event.setCurrentCity(bean.getName());
            event.setCurrentCityId(bean.getId());
            event.setPosition(0);
            EventBus.getDefault().post(event);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    private void getChannelList() {
        //网络获取省市选择器内容list，然后在成功回调中获取List<CityChannelBean>然后便利ListChannelBean获取对应的fragment
        //也就是，setFragments()是在getChannelList的成功回调中调用即可
        if(spu.getCurrentCountry() != null) {

            mList = spu.getCurrentCountry().getChild();
            cityTablepageLl.setVisibility(View.VISIBLE);
            setFragments(mList);
        }else{
            AreaChannelBean areaChannelBean = new AreaChannelBean();
            areaChannelBean.setName(spu.getCurrentCity());
            areaChannelBean.setId(spu.getCurrentCityId());
//            NanningItemFragment cityitem = NanningItemFragment.newInstance(areaChannelBean);
            mList.clear();
            mList.add(areaChannelBean);
            cityTablepageLl.setVisibility(View.GONE);
            setFragments(mList);
        }
    }

    private void JustgetChannelList(){
        if(spu.getCurrentCountry() != null) {
            mList = spu.getCurrentCountry().getChild();
            cityTablepageLl.setVisibility(View.VISIBLE);
        }else{
            cityTablepageLl.setVisibility(View.GONE);
        }
//        List<AreaChannelBean> mList2 = new ArrayList<>();
//        AreaChannelBean item2 = new AreaChannelBean();
//        item2.setName(spu.getCurrentCity());
//        item2.setId(spu.getCurrentCityId());
//        mList2.add(item2);
//        adapter.sortChannel(mList2);
//        citypager.setOffscreenPageLimit(adapter.getCount());
    }
    private void setFragments(List<AreaChannelBean> myList) {
        if (null == myList) {
            myList = new ArrayList<AreaChannelBean>();
        }
        LogUtils.i("mlist_size-->" + myList.size());
        if(newsItemFragmentList == null){
            newsItemFragmentList = new ArrayList<>();
        }else{
            newsItemFragmentList.clear();
        }
        for (int i = 0; i < myList.size(); i++) {

            AreaChannelBean ccb = myList.get(i);
            NanningItemFragment fragment = NanningItemFragment.newInstance(ccb);
            fragment.setTitle(ccb.getName());
            LogUtils.i("name-->"+ccb.getName());
            newsItemFragmentList.add(fragment);
        }
        if (newsItemFragmentList.size() > 0 && spu.getCurrentCountry() != null) {
            cityTablepageLl.setVisibility(View.VISIBLE);
        }
        adapter.setFragments(newsItemFragmentList);
        citypager.setOffscreenPageLimit(adapter.getCount());
        indicator.setViewPager(citypager);
//        if(newsItemFragmentList.size()>5){
//            mydivider.setVisibility(View.VISIBLE);
//        }else{
//            mydivider.setVisibility(View.GONE);
//        }
//        if(newsItemFragmentList.size()>5){
//            indicator.setPadding(0,0,70,0);
//        }else{
//            indicator.setPadding(0,0,0,0);
//        }
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                NewsBaseFragment frag = (NewsBaseFragment) adapter.getItem(position);
                frag.init();
                spu.setCurrentCountryPosition(position);
                adapter.setSelectedPosition(position);
                CurrentCityEventForMainAndZiXun eventForMainAndZiXun = new CurrentCityEventForMainAndZiXun();
                EventBus.getDefault().post(eventForMainAndZiXun);
                if(spu.getCurrentCountry() != null){
                    tvCityId.setText(spu.getCurrentCountry().getChild().get(position).getName());
                }
            }
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }
            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
        if(spu.getCurrentCountryPosition() != -1){
            indicator.setCurrentItem(spu.getCurrentCountryPosition());
        }
    }

    public void init() {

    }

    public void setIsNeedRefresh() {
        isNeedRefresh = true;
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    public String getTitle() {
        return mTitle;
    }


//    private NewsCancelDialog dialog;

    //点击时间
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
        final NewsBean newsBean = (NewsBean) adapter.getItem(position);
        switch (view.getId()) {
            case R.id.newsItem_root:
                ////REFACTOR: 2017/8/18 添加浏览量bug
//                addCount(newsBean);
                MyActivitymanager.pushActivity(activity, newsBean, newsBean.getTid(), "newsitem", newsBean.getRvalue());
                LogUtils.e("rtype--" + newsBean.getRtype());
                break;
        }
    }

    /**
     * 不感兴趣
     */
    private void getWeather() {
        Map<String, String> map = new HashMap<>();
        map.put("city",spu.getCurrentCity());
        Factory.provideHttpService2().getWeather(InterfaceJsonfile.WEATHER+spu.getCurrentCity())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<WeatherBean>() {
                    @Override
                    public void call(WeatherBean bean) {
                        tvWeatherId.setText(bean.getData().getForecast().get(0).getType()+"  "+bean.getData().getWendu() + " ℃");
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("异常-->" + throwable.toString());
                    }
                });
    }

    public void setListData(List<NewsBean> list) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    //当前城市,
    @Subscribe
    public void onEventMainThread(CurrentCityEvent event) {
        getChannelJson2();
        getWeather();

    }
    //当前城市,
    @Subscribe
    public void onEventMainThread(CurrentSecondCityEvent event) {
        LogUtils.i("3city-->"+event.getPosition());
        JustgetChannelList();
        if(event.getPosition() != -1) {
            adapter.sortChannel(mList);
            citypager.setOffscreenPageLimit(adapter.getCount());
            indicator.notifyDataSetChanged();
            indicator.setCurrentItem(event.getPosition());
        }else{
            List<AreaChannelBean> mList2 = new ArrayList<>();
            AreaChannelBean item2 = new AreaChannelBean();
            item2.setName(event.getCurrentCity());
            item2.setId(spu.getCurrentCityId());
            mList2.add(item2);
            adapter.sortChannel(mList2);
            citypager.setOffscreenPageLimit(adapter.getCount());
        }
        if(spu.getCurrentCountry() != null){
            tvCityId.setText(spu.getCurrentCountry().getChild().get(spu.getCurrentCountryPosition()).getName());
        }else{
            tvCityId.setText(spu.getCurrentCity());
        }
        getWeather();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        unbinder.unbind();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder1 = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick({R.id.imageView, R.id.ll_city_id})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_city_id:
                PageCtrl.start2ChangeCityActivity(activity);
                break;
        }
    }

    //获取,栏目title;
    private void getChannelJson() {
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        if(spu.getCurrentCityId() != null){
            map.put("id",spu.getCurrentCityId());
        }else {
            map.put("id", "1");
        }
        Factory.provideHttpService()
                .getArealist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<AreaChannelEntity, Boolean>() {
                    @Override
                    public Boolean call(AreaChannelEntity entity) {
                        LogUtils.e("code--" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<AreaChannelEntity>() {
                    @Override
                    public void call(AreaChannelEntity entity) {
                        SPUtil.getInstance().setCurrentCity(entity.data.getOther().get(0).getName());
                        SPUtil.getInstance().setCurrentCityId(entity.data.getOther().get(0).getId());
                        SPUtil.getInstance().setCurrentCounty(entity.data.getOther().get(0));
                        LogUtils.i("othercountry-->"+entity.data.getOther().get(0).getName());
                        SPUtil.getInstance().setCurrentCountryPosition(0);
                        SPUtil.getInstance().setIsLarge(entity.data.getOther().get(0).getIslarge());
                        getChannelList();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable-->" + throwable.toString());
                    }
                });
    }
    //获取,栏目title;
    private void getChannelJson2() {
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        if(spu.getCurrentCityId() != null){
            map.put("id",spu.getCurrentCityId());
        }else {
            map.put("id", "1");
        }
        Factory.provideHttpService()
                .getArealist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<AreaChannelEntity, Boolean>() {
                    @Override
                    public Boolean call(AreaChannelEntity entity) {
                        LogUtils.e("code--" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<AreaChannelEntity>() {
                    @Override
                    public void call(AreaChannelEntity entity) {
                        SPUtil.getInstance().setCurrentCity(entity.data.getOther().get(0).getName());
                        SPUtil.getInstance().setCurrentCityId(entity.data.getOther().get(0).getId());
                        SPUtil.getInstance().setCurrentCounty(entity.data.getOther().get(0));
                        LogUtils.i("othercountry-->"+entity.data.getOther().get(0).getName());
                        SPUtil.getInstance().setCurrentCountryPosition(0);
                        SPUtil.getInstance().setIsLarge(entity.data.getOther().get(0).getIslarge());
                        JustgetChannelList();
                        adapter.sortChannel(mList);
                        citypager.setOffscreenPageLimit(adapter.getCount());
                        indicator.notifyDataSetChanged();
                        if(spu.getCurrentCountry() != null){
                        tvCityId.setText(spu.getCurrentCountry().getChild().get(spu.getCurrentCountryPosition()).getName());
        }else{
            tvCityId.setText(spu.getCurrentCity());
        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable-->" + throwable.toString());
                    }
                });
    }
}

